<template>
  <div v-loading="loading">
    <text v-if="!userinfo" class="text-center" @click="openlogin">登录/注册</text>
    <div
      v-else
      class="cursor-pointer whitespace-nowrap text-center"
      v-popover="popoverRef"
      v-click-outside="onClickOutside"
      role="menuitem"
    >
      <div
        class="flex items-center"
        style="margin-left: 20px"
        @click="popoverShow = true"
        v-click-outside="onClickOutside"
      >
        <img :src="userinfo.uAvatar" alt="avatar" class="rounded-full mr-2" style="width: 30px" />
        {{ userinfo.uNikename }}
      </div>
    </div>
    <el-popover ref="popoverRef" :visible="popoverShow" width="200px" trigger="click" virtual-triggering persistent>
      <div>
        <el-menu default-active="1" class="el-menu-vertical-demo" @select="handleSelect">
          <el-menu-item index="1" style="width: 100%">
            <el-icon>
              <Avatar />
            </el-icon>
            <span>个人信息</span>
          </el-menu-item>
          <el-menu-item index="2" style="width: 100%">
            <el-icon>
              <Grid />
            </el-icon>
            <span>管理后台</span>
          </el-menu-item>
          <el-menu-item index="3" style="width: 100%">
            <el-icon><List /></el-icon>
            <span>成员列表</span>
          </el-menu-item>

          <el-menu-item index="4" style="width: 100%">
            <el-icon>
              <SwitchButton />
            </el-icon>
            <span>安全退出</span>
          </el-menu-item>
        </el-menu>
      </div>
    </el-popover>
    <el-dialog v-model="logindialogVisible" title="个人信息" width="1000">
      <div style="height: 600px">
        <el-row gutter="20">
          <el-col :span="12">
            <el-form :model="userinfo">
              <div class="block mb-8">
                <el-upload
                  action="#"
                  :http-request="UploadOss"
                  list-type="text"
                  :auto-upload="true"
                  :accept="accept"
                  :show-file-list="false"
                  :on-progress="uploadVideoProcess"
                >
                  <img :src="userinfo.uAvatar" class="w-20 h-20 rounded-full" />
                </el-upload>
              </div>
              <el-form-item label="昵称" prop="uNikename">
                <el-input v-model="userinfo.uNikename" />
              </el-form-item>
              <el-form-item label="电话" prop="uPhone">
                <el-input readonly="true" disabled="true" v-model="userinfo.uPhone" />
              </el-form-item>
            </el-form>
          </el-col>
          <el-col :span="12">
            <div v-if="!f" class="w-full flex justify-center items-center" style="height: 600px; overflow: scroll">
              <div class="text-right" style="font-size: 24rpx" @click="zyy">转为企业账号</div>
            </div>
            <div v-else>
              <div style="height: 600px; overflow: scroll">
                <el-form :model="c">
                  <div class="block mb-8">
                    <el-upload
                      action="#"
                      :http-request="UploadOss"
                      list-type="text"
                      :auto-upload="true"
                      :accept="accept"
                      :show-file-list="false"
                      :on-progress="uploadVideoProcess"
                    >
                      <img :src="c.companyLogo" class="w-40" />
                    </el-upload>
                  </div>
                  <el-form-item label="企业名称" prop="companyName">
                    <el-input v-model="c.companyName" />
                  </el-form-item>
                  <el-form-item label="企业简介" prop="description">
                    <el-input type="textarea" v-model="c.description" />
                  </el-form-item>
                  <el-upload
                    action="#"
                    :http-request="UploadOss2"
                    list-type="picture-card"
                    :auto-upload="true"
                    multiple
                    limit="9"
                    :file-list="fileList1"
                    :accept="accept"
                    style="max-height: 100px; padding: 20px; margin: 0 auto"
                  >
                    <el-icon><Plus /></el-icon>
                    <template #file="{ file }">
                      <div>
                        <img class="el-upload-list__item-thumbnail" :src="file.url" alt="" />
                        <span class="el-upload-list__item-actions">
                          <!-- <span class="el-upload-list__item-preview" @click="handlePictureCardPreview(file)">
                            <el-icon><zoom-in /></el-icon>
                          </span>
                          <span v-if="!disabled" class="el-upload-list__item-delete" @click="handleDownload(file)">
                            <el-icon><Download /></el-icon>
                          </span> -->
                          <span class="el-upload-list__item-delete" @click="handleRemove(file)">
                            <el-icon><Delete /></el-icon>
                          </span>
                        </span>
                      </div>
                    </template>
                  </el-upload>

                  <div style="padding: 40rpx">
                    <el-radio-group v-model="radiovalue">
                      <div class="w-full">
                        <el-radio :style="{ margin: '8px' }" label="方式一：展示亿码互联logo" :value="0"> </el-radio>
                      </div>
                      <div class="border w-full">
                        <div class="button-group mt-10">
                          <el-button class="button-item">收藏</el-button>
                          <el-button class="button-item">分享</el-button>
                        </div>
                        <div class="text-center h-10 w-full" style="font-size: 14px">
                          <span class="text-blue-500" @click="gohome2()"> 亿码互联 </span>提供技术支持
                        </div>
                      </div>
                      <div class="w-full mt-4">
                        <el-radio :style="{ margin: '8px' }" label="方式二：展示企业自定义logo" :value="1"> </el-radio>
                      </div>
                      <div class="border w-full mt-4">
                        <div class="button-group mt-10">
                          <el-button class="button-item">收藏</el-button>
                          <el-button class="button-item">分享</el-button>
                        </div>
                        123
                        <div class="text-center h-10 w-full" style="font-size: 14px">
                          <span class="text-blue-500" @click="gohome2()">
                            {{ c.companyName ? c.companyName : 'XXXXXX' }} </span
                          >提供技术支持
                        </div>
                      </div>
                      <div class="w-full mt-4">
                        <el-radio
                          :style="{ margin: '8px' }"
                          :disabled="vipinfo.viptmpId <= 1"
                          label="方式三：自动隐藏logo（VIP会员升级）"
                          :value="2"
                        >
                        </el-radio>
                      </div>
                      <div class="border w-full mt-4">
                        <div class="button-group mt-10">
                          <el-button class="button-item">收藏</el-button>
                          <el-button class="button-item">分享</el-button>
                        </div>
                      </div>
                    </el-radio-group>
                  </div>
                </el-form>
              </div>
            </div>
          </el-col>
        </el-row>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogFormVisible = false">Cancel</el-button>
          <el-button type="primary" @click="onSubmit"> 保存 </el-button>
        </div>
      </template>
    </el-dialog>
    <el-dialog v-model="logindialogVisible2" title="成员列表" width="1000">
      <el-dialog v-model="innerVisible" width="500" append-to-body>
        <div style="height: 60vh; padding: 20px">
          <div style="font-size: 16px; font-weight: bold; color: #bd3124">
            {{ text }}
          </div>
          <div style="margin-top: 20px">姓名<text style="color: #bd3124"> * </text></div>
          <div style="margin-top: 20px">
            <el-input v-model="username" placeholder="请输入内容" border="surround"></el-input>
          </div>
          <div style="margin-top: 20px">手机<text style="color: #bd3124"> * </text></div>
          <div style="margin-top: 20px">
            <el-input v-model="userphone" maxlength="11" placeholder="请输入内容" border="surround"></el-input>
          </div>
          <div style="margin-top: 20px">权限<text style="color: #bd3124"> * </text></div>
          <div>
            <el-radio-group v-model="radiovalue2">
              <el-radio :value="2" size="large" border style="height: 60px; margin-top: 20px">
                <div class="w-full p-2 m-1" style="width: 360px">
                  <div style="font-size: 14px; font-weight: bold; color: #000">协作人员</div>
                  <div style="margin-top: 5px; font-size: 12px">可接收组织内消息提醒，@他人参与协作。</div>
                </div>
              </el-radio>
              <br />
              <el-radio :value="1" size="large" border style="height: 60px; margin-top: 20px">
                <div class="w-full p-2 m-1" style="width: 360px">
                  <div style="font-size: 14px; font-weight: bold; color: #000">子管理员</div>
                  <div style="margin-top: 5px; font-size: 12px">可协助超级管理员管理活码，审核，接收消息等。</div>
                </div>
              </el-radio>
            </el-radio-group>
          </div>
          <div class="text-center mt-8">
            <el-button type="primary" style="margin: 0 auto" @click="saveadmin">保存</el-button>
          </div>
        </div>
      </el-dialog>
      <div>
        <el-button type="success" @click="addadmin">添加</el-button>
      </div>
      <div style="height: 600px; overflow: scroll">
        <el-table :data="adminlist" style="width: 100%">
          <el-table-column label="头像" width="150" header-align="center">
            <template #default="scope">
              <img
                :src="scope.row.accountUseravatar"
                class="h-15 w-15"
                style="margin: 0 auto; border-radius: 50%"
                @click="openImg(scope.row)"
              />
            </template>
          </el-table-column>
          <el-table-column label="类别" width="150" header-align="center">
            <template #default="scope">
              <el-tag v-if="scope.row.userType === 1" type="primary">子管理员</el-tag>
              <el-tag v-else type="warning">协作人员</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="userName" label="用户名" width="180" />
          <el-table-column prop="userPhone" label="电话号" />
          <el-table-column label="操作" width="250">
            <template #default="scope">
              <el-tooltip class="box-item" effect="dark" content="修改">
                <el-button type="info" icon="Edit" circle @click="edit(scope.row)" />
              </el-tooltip>
              <el-tooltip class="box-item" effect="dark" content="删除">
                <el-button type="danger" icon="Delete" circle @click="del(scope.row)" />
              </el-tooltip>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, toRefs, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import { fileput, formatBytes } from '@/utils/ali-oss';
import moment from 'moment';
import { ClickOutside as vClickOutside } from 'element-plus';
import { ElMessage, ElMessageBox } from 'element-plus';
import {
  userinfo_saveone,
  i50_companyinfo_one,
  i31_staff_saveone,
  i32_staff_list,
  i33_staffaccount_list,
  i34_usercheck_one,
} from '@/api/index.js';
import DialogHandle from '@/views/components/dialog.js';
const showToast = inject('showToast');
const loading = ref(true);
loading.value = false;
let userinfo = ref({});
let vipinfo = ref({});
const logindialogVisible = ref(false);
const logindialogVisible2 = ref(false);
const innerVisible = ref(false);
const router = useRouter();
//localStorage.setItem('userinfo', '{"createBy":null,"createTime":null,"updateBy":null,"updateTime":null,"remark":null,"id":1,"uWxOpenid":"oMeua61EGEYZcJebCHPWpaWFaYNI","uPhone":"18624024313","uNikename":"羽然香","ueId":null,"uAvatar":"https://ecodeuserstore.oss-cn-beijing.aliyuncs.com/UserAvatar/YfidCMsBwn.jpeg","uShareratio":null,"createdTime":"2024-04-19 05:17:00","updatedTime":null,"uState":0,"pDistribuUserid":null,"uLevel":null,"isDistritution":null,"uVipLevel":null,"limitImgtxtone":6291456,"limitImgtxtsum":100,"limitAudiovideoone":62914560,"limitAudiovideosum":100,"vipName":"vip1","user_companyName":null}')
userinfo.value = JSON.parse(localStorage.getItem('userinfo'));
vipinfo.value = JSON.parse(localStorage.getItem('vipinfo'));
const f = ref(false);
console.log('userinfo.value :', userinfo.value);
const popoverRef = ref();
const popoverShow = ref(false);
function openlogin() {
  const dialog = DialogHandle({
    title: '请登录',
    content: '<div class="text-center">打开微信扫一扫登录系统</div>',
    onConfirm: () => {
      return new Promise(async (resolve) => {
        dialog.showLoading();
        setTimeout(() => {
          dialog.hideLoading();
          resolve();
        }, 1500);
      });
    },
  });
}
const adminlist = ref([]);
function getData() {
  i32_staff_list({
    userId: userinfo.value.id,
    creatorId: userinfo.value.id,
    token: userinfo.value.uWxOpenid,
  }).then((res) => {
    if (res.data.code == 200) {
      console.log('res', res);
      adminlist.value = res.data.data.listdata;
      logindialogVisible2.value = true;
    } else {
      // uni.showToast({
      //   title: res.msg,
      //   icon: 'none',
      //   duration: 2000,
      // })
    }
  });
}
const text = ref('新增成员');
const radiovalue2 = ref(2);
const organizId = ref(0);
const username = ref('');
const userphone = ref('');
function addadmin() {
  organizId.value = 0;
  username.value = '';
  userphone.value = '';
  radiovalue2.value = 2;
  innerVisible.value = true;
}
function edit(o) {
  text.value = '修改成员';
  console.log('o:', o);
  organizId.value = o.organizId;
  username.value = o.userName;
  userphone.value = o.userPhone;
  radiovalue2.value = o.userType;
  innerVisible.value = true;
}
function del(item) {
  ElMessageBox.confirm(`您确定要删除吗?`, '删除提示', {
    confirmButtonText: '删除',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(() => {
    //if (res.confirm) {
    //console.log('res:', res);
    i31_staff_saveone({
      userName: item.userName,
      userPhone: item.userPhone,
      userIdAdd: item.userId,
      organizId: 0,
      deleteId: item.organizId,
      userType: item.userType,
    }).then((res) => {
      if (res.data.code == 200) {
        console.log('res', res);
        ElMessage({
          message: '删除成功',
          type: 'success',
        });

        getData();
      } else {
        ElMessage({
          message: res.data.msg,
          type: 'error',
        });
      }
    });
    //}
  });
}
function saveadmin() {
  if (username.value == '') {
    ElMessage({
      message: '请输入姓名',
      type: 'info',
    });
  } else if (userphone.value == '') {
    ElMessage({
      message: '请输入手机号',
      type: 'info',
    });
  } else {
    i34_usercheck_one(userphone.value).then((r) => {
      if (r.data.code == 200) {
        i31_staff_saveone({
          userName: username.value,
          userPhone: userphone.value,
          organizId: organizId.value,
          userIdAdd: r.data.data.userinfo.id,
          deleteId: 0,
          userType: radiovalue2.value,
        }).then((res) => {
          if (res.data.code == 200) {
            console.log('res', res);
            ElMessage({
              message: '添加成功',
              type: 'success',
            });

            getData();
            innerVisible.value = false;
          } else {
            ElMessage({
              message: res.data.msg,
              type: 'error',
            });
          }
        });
      } else {
        ElMessage({
          message: r.data.msg,
          type: 'error',
        });
      }
    });
  }
}
const handleRemove = (file) => {
  console.log(file);
  const index = fileList1.value.findIndex((item) => item.url === file.url);
  console.log('index:', index);
  // 在imageIds数组中找到它！干掉它！
  fileList1.value.splice(index, 1);
};
/**点击空白处隐藏 */
const onClickOutside = (e) => {
  // console.log('onClickOutside', e);
  if (popoverShow.value && !unref(popoverRef).popperRef.contentRef.contains(e.target)) {
    popoverShow.value = false;
  }
};
const handleSelect = (key, keyPath) => {
  console.log(key, keyPath);
  switch (key) {
    case '1':
      logindialogVisible.value = true;
      break;
    case '2':
      router.push('/admin');
      break;
    case '3':
      getData();

      break;
    case '4':
      loginout();
      break;
  }
};
function loginout() {
  //删除 localStorage 中的 userinfo
  localStorage.removeItem('userinfo');
  userinfo.value = null;
  popoverShow.value = false;
}
function UploadOss(option) {
  //progressFlag.value = true;
  console.log(option);
  let objName = option.file.name;
  let fileName = moment().format('YYYY/MM/DD');
  //this.uploadLoading = true
  fileput(`pc/${fileName}/${objName}`, option.file).then((res) => {
    console.log(res);
    if (res.res.statusCode === 200) {
      console.log('上传成功', res);
      userinfo.value.uAvatar = res.url;
      console.log('userinfo.value.uAvatar:', userinfo.value.uAvatar);
    }
  });
}
const c = ref({});
const fileList1 = ref([]);
const radiovalue = ref(0);
function zyy() {
  f.value = true;
  if (userinfo.value.ueId > 0) {
    i50_companyinfo_one(userinfo.value.ueId).then((res) => {
      console.log('res:', res);
      c.value = res.data.data.companyinfo;
      fileList1.value = JSON.parse(res.data.data.companyinfo.licenseMore);
      radiovalue.value = res.data.data.companyinfo.companyflagShow;
      console.log('radiovalue.value:', radiovalue.value);
    });
  }
  //this.$refs.popup.open('bottom');
}
function UploadOss2(option) {
  //progressFlag.value = true;
  console.log(option);
  let objName = option.file.name;
  let fileName = moment().format('YYYY/MM/DD');
  //this.uploadLoading = true
  fileput(`pc/${fileName}/${objName}`, option.file).then((res) => {
    console.log(res);
    if (res.res.statusCode === 200) {
      console.log('上传成功', res);
      fileList1.value.push({ size: option.file.size, type: 'image', url: res.url });
    }
  });
}
console.log(vipinfo.value);
if (vipinfo.value !== null && userinfo.value !== null) {
  if (vipinfo.value.vipName !== '免费版' && userinfo.value.ueId > 0) {
    console.log('222:');
    f.value = true;
    i50_companyinfo_one(userinfo.value.ueId).then((res) => {
      console.log('res:', res);
      c.value = res.data.data.companyinfo;
      fileList1.value = JSON.parse(res.data.data.companyinfo.licenseMore);
      console.log('fileList1.value:', fileList1.value);
      radiovalue.value = res.data.data.companyinfo.companyflagShow;
      console.log('radiovalue.value:', radiovalue.value);
    });
  }
}
function onSubmit() {
  // 这里做自己公司的存储逻辑
  //console.log('this.user', this.user);
  console.log('fileList1.value:', fileList1.value);
  console.log('radiovalue.value:', radiovalue.value);
  userinfo_saveone(userinfo.value).then((res) => {
    if (res.data.code === 200) {
      ElMessage({
        message: '保存成功',
        type: 'success',
      });
      logindialogVisible.value = false;
    } else {
      ElMessage({
        message: '保存失败',
        type: 'error',
      });
    }
  });
}
onMounted(() => {});
</script>
<style>
.el-upload--picture-card {
  width: 60px !important;
  height: 60px !important;
}

.el-upload-list--picture-card .el-upload-list__item {
  width: 60px !important;
  height: 60px !important;
}

.button-group {
  display: flex;
  margin: 30px 60px;
}

.button-item {
  flex: 1;
  padding: 10px;
  text-align: center;
  cursor: pointer;
  border: 1px solid #ccc;
  border-left: none;
}

.button-group .button-item:first-child {
  border-left: 1px solid #ccc;
  border-radius: 20px 0 0 20px;
}

.button-group .button-item:last-child {
  border-radius: 0 20px 20px 0;
}

.button-group .button-item:not(:first-child, :last-child) {
  border-radius: 0;
}
</style>
<style scoped lang="less"></style>

